﻿
using Main.Extend;
using Main.Extend.Attributes;
using Microsoft.Extensions.Configuration;

namespace Main.Common
{
    /// <summary>
    /// 阿里云验证码帮助类
    /// </summary>
    [Provider, Inject]
    public class SendCode : BaseCommon
    {

        private AlibabaCloud.SDK.Dysmsapi20170525.Client CloudClient;

        public SendCode(IConfiguration configuration) : base(configuration)
        {

            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config()
            {
                AccessKeyId = _Config["AliYun:AccessKey"],
                AccessKeySecret = _Config["AliYun:AccessKeySecret"],
                Endpoint = "dysmsapi.aliyuncs.com",
            };
            CloudClient = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="Phone">手机号</param>
        /// <param name="code">验证码</param>
        /// <returns>返回值不等于 字符串 OK 就是发送失败</returns>
        public string SendPhoneCode(string Phone, string code)
        {
            if (Phone.IsNullOrEmpty())
            {
                return "电话号码为空";
            }
            if (Phone.IsNullOrEmpty())
            {
                return "验证码为空";
            }
            if (Phone.Length != 11)
            {
                return "电话号码长度必须是11位";
            }

            AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest SmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest()
            {
                TemplateCode = _Config["AliYunCode:TemplateCode"],
                PhoneNumbers = Phone,
                SignName = _Config["AliYunCode:SignName"],
                TemplateParam = "{\"code\":\"" + code + "\"}"
            };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                var CodeResonse = CloudClient.SendSmsWithOptions(SmsRequest, runtime);
                return CodeResonse.Body.Message;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
